<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class LangClassLessonFile extends \app\common\model\LangClassLessonFile
{
    /**
     * 免费视频列表
     * @param int $page 第几页
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function freeList($page, $size)
    {
        $offset = ($page - 1) * $size;
        $where = [
            'status' => StatusEnum::ENABLED,
            'type' => self::TYPE_VIDEO,
            'is_free' => self::FREE
        ];
        $model = static::field('id as fileId, lesson_id AS lessonId, file_name AS fileName')
            ->where($where)
            ->order(['sort_num' => 'desc', 'create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        $count = static::where($where)->count();
        return [
            'list' => $model,
            'count' => $count
        ];
    }

    /**
     * 通过每节课id和类型查找视频等列表
     * @param int $classId 班级id
     * @param int $lessonId 每节课id
     * @param int $type 文件类型，视频1，音频2，学习资料课件下载3，学习资料随堂作业4
     * @param int $page 页数
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getListByLesson($classId, $lessonId, $type, $page, $size)
    {
        // 试听详情里面的不知道第一节课的id，只能通过班级id和类型查找
        if ($lessonId <= 0) {
            // 通过班级查找第一节课
            $first = LangClassLesson::getFirst($classId, $type);
            if (empty($first)) {
                return [
                    'list' => [],
                    'count' => 0,
                ];
            } else {
                $lessonId = $first['id'];
            }
        }

        $offset = ($page - 1) * $size;

        // 不返回文件路径，点击的时候再请求判断是否已经购买
        $sql = static::where([
            'lesson_id' => $lessonId,
            'type' => $type,
            'status' => StatusEnum::ENABLED
        ]);

        $model = $sql->field('id AS fileId, file_name AS fileName, is_free AS isFree, create_time AS createTime')
            ->order(['sort_num' => 'desc', 'lesson_id' => 'asc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['createTime'] = date('Y-m-d', $value['createTime']);
        }

        return [
            'list' => $model,
            'count' => $sql->count(),
        ];
    }

    /**
     * 通过lessonId查找班级，判断是否已经购买
     * @param $oauthId
     * @param $lessonId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function canByLesson($oauthId, $lessonId)
    {
        // 通过lessonId查找对应班级id
        $class = LangClassLesson::getClass($lessonId);
        if (empty($class)) {
            return false;
        }

        // 非免费，判断是否已经购买
        $one = OauthOrderClass::getOneByClass($oauthId, $class['class_id']);
        return $one ? true : false;
    }

    /**
     * 判断指定文件是否能看
     * @param $oauthId
     * @param $fileId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function canWatch($oauthId, $fileId)
    {
        // 查找文件对应的班级
        $class = static::field('l.class_id, f.file, f.type, f.is_free, f.type, f.description')
            ->alias('f')
            ->join('lang_class_lesson l', 'l.id = f.lesson_id')
            ->where(['f.id' => $fileId, 'f.status' => StatusEnum::ENABLED, 'l.status' => StatusEnum::ENABLED])
            ->find();
        if (empty($class)) {
            return [
                'classId' => 0,
                'file' => '',
                'fileType' => 0,
                'description' => '',
                'canWatch' => false
            ];
        }

        $file = '';
        $canWatch = false;
        // 免费视频可以观看
        if ($class['is_free'] == self::FREE) {
            $canWatch = true;
        } else {
            // 非免费，判断是否已经购买
            $one = OauthOrderClass::getOneByClass($oauthId, $class['class_id']);
            if ($one) {
                $canWatch = true;
            }
        }

        if ($canWatch === true) {
            $file = config('file_prefix') . $class['file'];

            // 视频、音频、课件添加或者更新我的轨迹记录
            if (in_array($class['type'], self::WATCH_LOG_ARR)) {
                OauthWatchLog::addOne($oauthId, $fileId);
            }
        }

        return [
            'classId' => $class['class_id'],
            'file' => $file,
            'fileType' => $class['type'],
            'description' => $class['description'],
            'canWatch' => $canWatch
        ];
    }
}